#include "dialog.h"
#include "ui_dialog.h"
#include <QTimer>
#include "register.h"

using namespace std;

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{

    ui->setupUi(this);
}

Dialog::~Dialog()
{
    delete usermanager;
    delete register_s;
    delete menuview1;
    delete admin1;
    delete ui;
}

static int c=0; //输错的次数

//登录按钮
void Dialog::on_pushButton_clicked()
{
    string username = ui->lineEdit_User->text().toStdString();
    string passwd = ui->lineEdit_passwd->text().toStdString();

    auto users = usermanager->returnUsers();  // 返回一个users的map
    auto it = users.find(username);     // 返回对应username的User对象

    if (it == users.end()) {
        // 用户未找到
        QMessageBox msgBOX;
        msgBOX.setWindowTitle("Login");
        msgBOX.setText("User not found!");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);
        msgBOX.exec();
        return;
    }

    // 检查密码是否正确
    if (it->second.checkPassword(passwd))
    {
        // 密码正确，登录成功
        if (!it->second.isAdminUser())
        {
            this->menu();
            this->close();
        }
        else
        {
            QMessageBox msgBOX;
            msgBOX.setWindowTitle("warning");
            msgBOX.setText("Please proceed to the administrator login!");
            msgBOX.setStandardButtons(QMessageBox::Ok);
            msgBOX.exec();
        }
        return;
    }

    // 密码错误，增加计数器
    c++;

    // 检查是否输错了五次
    if (c==3)
    {
        // 显示错误消息并等待30秒
        ui->pushButton->setEnabled(false); // 禁用按钮
        ui->lineEdit_passwd->setEnabled(false); // 禁用密码输入框

        QMessageBox msgBOX;
        msgBOX.setText("You have input wrong password three times,please wait 30 seconds");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);

        QTimer* timer = new QTimer(this);
        connect(timer, &QTimer::timeout, [&, timer]() {
            c=0;  // 重置计数值
            timer->deleteLater();  // 清理定时器对象
            ui->pushButton->setEnabled(true); // 恢复按钮
            ui->lineEdit_passwd->setEnabled(true); // 恢复密码输入框
        });

        timer->start(30000);  // 30秒后执行定时器操作

        msgBOX.exec();
    }
    else
    {
        // 显示密码错误消息
        QMessageBox msgBOX;
        msgBOX.setText("Incorrect password!");
        msgBOX.setStandardButtons(QMessageBox::Ok|QMessageBox::Cancel);
        msgBOX.exec();
    }
}

//注册按钮
void Dialog::on_pushButton_1_clicked()
{
    register_s->show();


}

